package com.ddshuai.easy;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 描述 新通教育
 * 给定两个由小写字母构成的字符串 A 和 B ，只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果，就返回 true ；否则返回 false 。
 * <p>
 * 输入： A = "ab", B = "ba"
 * 输出： true
 * <p>
 * <p>
 * 输入： A = "ab", B = "ab"
 * 输出： false
 * <p>
 * 输入： A = "aa", B = "aa"
 * 输出： true
 * <p>
 * 输入： A = "aaaaaaabc", B = "aaaaaaacb"
 * 输出： true
 * <p>
 * 输入： A = "", B = "aa"
 * 输出： false
 *
 * @author ddshuai
 * @date 2018-12-17 15:36
 **/
public class BuddyStrings {
    //交互相等
    public static boolean buddyStrings(String A, String B) {
        char[] as = A.toCharArray();
        char[] bs = B.toCharArray();
        List<Integer> diff = new ArrayList<>(10);
        if (as.length == bs.length) {
            if (A.equals(B)) {
                Set<Character> characterSet = new HashSet<>();
                for (char a : as) {
                    characterSet.add(a);
                }

                return as.length != characterSet.size();
            }
            for (int i = 0; i < as.length; i++) {
                if (as[i] != bs[i]) {
                    diff.add(i);
                }
            }
        }
        if (diff.size() == 2) {
            if (as[diff.get(0)] == bs[diff.get(1)] && as[diff.get(1)] == bs[diff.get(0)]) {
                return true;
            }
        }
        return false;
    }

    public static boolean buddyStrings1(String A, String B) {
        char[] as = A.toCharArray();
        char[] bs = B.toCharArray();
        int sum = 0;
        int first = -1;
        int second = -1;
        boolean hasDup = false;
        for (int i = 0; i < as.length; i++) {
            if (sum > 2) {
                return false;
            }
            if (A.indexOf(as[i],i+1) > -1){
                hasDup = true;
            }
            if (as[i] != bs[i]) {
                if (first > -1){
                    second = i;
                }else {
                    first = i;
                }
                sum++;
            }
        }

        if (first > -1 && second > -1){
            if (as[first] == bs[second] && as[second] == bs[first]) {
                return true;
            }
        }

        if (sum == 0){
            return hasDup;
        }

        return false;
    }

    public static void main(String[] args) {
        System.out.println(buddyStrings1("ba", "ba"));
    }
}
